#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstdio>
#include <thread>
#include <cstring>
#include "Log.hpp"
#include "terminal.hpp"
using namespace std;
// std::string serverip = "212.64.14.243";
// uint16_t serverport = 8888;
Log lg;

void Usage(const std::string& cmd)
{
    cout << "\n\r" << cmd << " serverip serverport" << endl << endl; 
}
struct ThreadData
{
    int sockfd_;
    sockaddr_in server_;
};
void sendMessage(const ThreadData& td)
{
    while(true)
    {
        string message;
        cout << "please say$ "; 
        getline(cin, message);
        sendto(td.sockfd_, message.c_str(), message.size(), 0, (const sockaddr *)&td.server_, sizeof(td.server_));
    }
}

void recvMessage(const ThreadData& td)
{
    while(true)
    {
        char buffer[1024];
        sockaddr_in temp;
        socklen_t size = sizeof(temp);
        ssize_t n = recvfrom(td.sockfd_, buffer, 1023, 0, (sockaddr *)&temp, &size);
        buffer[n] = 0;
        cerr << buffer << endl;
    }
}
int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }
    
    OpenTerminal();
    string ip = argv[1];
    uint16_t port = stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        //lg(Fatal, "create socket error, sockfd: %d", sockfd);
        return 2;
    }
    //lg(Info, "create socket success, sockfd: %d", sockfd);

    //不需要手动bind
    ThreadData td;
    struct sockaddr_in server;
    socklen_t len = sizeof(server);
    memset(&server, 0, len);
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(ip.c_str()); // 1.string->int 2.htonl
    server.sin_port = htons(port);
    td.sockfd_ = sockfd;
    td.server_ = server;
    thread send(sendMessage, td);
    thread recv(recvMessage, td);
    send.join();
    recv.join();
    close(sockfd);
    return 0;
}